﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Synthetic.Security.TripleDES
{
    public class TripleDESService
    {
        private ErrorHandler e = new ErrorHandler();

        private readonly byte[] KEY = new byte[]
        {
            217, 244, 254, 207, 218, 6, 126, 173, 182, 212, 241, 155, 246, 235, 4, 49, 33, 34, 212, 87, 32, 58, 124, 53
        };

        private readonly byte[] IV = new byte[]
        {
            38, 107, 163, 167, 22, 37, 86, 53
        };

        public void EncryptFile(string inputFile, string outputFile)
        {
            var crypto = new TripleDESCryptoServiceProvider()
            {
                Key = KEY,
                IV = IV
            };

            using (var inputStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
            {
                using (var outputStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                {
                    using (var cryptoStream = new CryptoStream(outputStream, crypto.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        inputStream.CopyTo(cryptoStream);
                    }
                }
            }
        }

        public void DecryptFile(string inputFile, string outputFile)
        {
            try
            {
                var crypto = new TripleDESCryptoServiceProvider()
                {
                    Key = KEY,
                    IV = IV
                };

                using (var inputStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
                {
                    using (var cryptoStream = new CryptoStream(inputStream, crypto.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        using (var outputStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                        {
                            cryptoStream.CopyTo(outputStream);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                e.AddBugToQueue(ex.ToString());
                e.Send();
            }
        }
    }
}
